<?php

/**
 * 根据用户权限显示对应的菜单栏
 */

namespace app\widgets;

use app\constants\Acl;
use app\models\Group;
use app\services\AdminService;
use yii\base\Widget;
use yii;

class MenuWidget extends Widget
{
    public function run()
    {
        /**
 * 获得用户的信息以及对应的权限
 * --------------------
 * 。。。。。。。
 * -------------------
 */
        //根据权限判断能显示的菜单栏  当groupId等于1时，显示全部的菜单
        $groupId      = AdminService::getLoginGroupIdFromSession();
        $groupModel   = new Group();
        $userGroup    = $groupModel->dbGet(['groupAcl'], '', ['where' => ['id' => $groupId]]);
        $loginUserAcl = $userGroup['groupAcl'];
        $currentAcl   = explode(',', $loginUserAcl);
        $allAcl       = Acl::$aclConfig;
        //能显示的菜单
        $menuList = [];
        foreach ($allAcl as $key => $item) {
            //如果模块权限在用户的权限
            if (in_array($item['acl'], $currentAcl) || $groupId == 1) {
                //如果二级子菜单的总权限有
                $menuList[$key] = [
                    'name'   => $key,
                    'url'    => $item['url'],
                    'acl'    => $item['acl'],
                    'action' => $item['action'],
                ];
                $sub            = [];
                foreach ($item['action'] as $k => $v) {
                    if (in_array($v['acl'], $currentAcl) || $groupId == 1) {
                        $sub[] = [
                            'name' => $v['name'],
                            'url'  => $v['url'],
                            'acl'  => $v['acl'],
                        ];
                    }
                }
                $menuList[$key]['sub'] = $sub;
            }
        }
        $controllerId = Yii::$app->controller->id;
        $actionId     = Yii::$app->controller->action->id;
        $acl          = $controllerId . '_' . $actionId;
        $assign       = [
            'acl'      => $acl,
            'menuList' => $menuList,
        ];
        return $this->render('menu', $assign);
    }
}
